import readline from "readline";
import routes from "../src/routes/routes.js";
import deepClone from "../src/tools/deepClone.js";
import {routesTemplate} from "./template.js";
import fs from "fs";
import {join} from "path";

const read = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let componentPath = '';
const routers = deepClone(routes);
const removeFile = (path)=>{
    const fileList = fs.readdirSync(path);
    for(const item of fileList){
        let fPath = join(path, item);
        let stat = fs.statSync(fPath);
        if(stat.isFile()){
            fs.unlinkSync(fPath)
        }else if(stat.isDirectory()){
            removeFile(fPath);
        }
    }
    fs.rmdirSync(path);
}
const getPath = (routePath,routers)=>{
    for(const index in routers){
        if(routers[index].path === routePath){
            componentPath = routers[index].componentPath;
            routers.splice(index,1);
            return;
        }
        if(routers[index].children.length>0){
            getPath(routePath,routers[index].children);
        }
    }
}
const removeRoute = (path)=>{
    getPath(path,routers);
    if(componentPath === ''){
        console.log('此路由不存在');
        read.close();
        return;
    }
    const filePath = componentPath.split('/').splice(2,Infinity).join('/');
    fs.writeFileSync('./src/routes/routes.js',routesTemplate(`const routes = ${JSON.stringify(routers)}`))
    read.question(`路由删除成功,是否同步删除${filePath}下的文件以及文件夹（y/N）`,(answer)=>{
        if(answer !== 'Y'){
            console.log('取消删除文件');
            read.close();
            return;
        }
        removeFile(filePath)
        console.log('文件删除完成');
        read.close();
    })
}
read.question('请输入需要删除的路由地址：（例如：/home/user）',(path)=>{
    removeRoute(path)
})